package com.qf.ability.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.qf.commons.data.result.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * author Ken
 * create_time 2022/9/21
 */
@RestController
@RequestMapping("/file/img")
@Slf4j
public class ImageController {

    private String uploadPath = "D://imgs";

    /**
     * 图片上传
     */
    @RequestMapping("/uploader")
    public Object uploader(MultipartFile file, Integer type){
        File myfile = new File(uploadPath);
        if (!myfile.exists()) myfile.mkdirs();
        //生成文件名称
        String filename = UUID.randomUUID().toString();
        try(
                //上传的输入流
                InputStream in = file.getInputStream();
                //输出的输出流
                OutputStream out = new FileOutputStream(new File(myfile,filename));
        ) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (type != null && type == 1) {
            //专门用来处理前端富文本上传的逻辑
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("errno", 0);
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("url", "http://192.168.0.110/file/img/download?imgName=" + filename);
            jsonObject.put("data", jsonObject2);
            return jsonObject.toJSONString();
        } else {
            return R.create(filename);
        }
    }

    /**
     * 图片下载/访问
     */
    @RequestMapping("/download")
    public void downLoad(String imgName, HttpServletResponse response){
        log.debug("[img download] 获取图片 - {}", imgName);
        try (
                InputStream in = new FileInputStream(new File(uploadPath, imgName));
                ServletOutputStream out = response.getOutputStream();
        ) {
                IOUtils.copy(in, out);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
